package com.qf.controller;

import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsAdminService;
import com.qf.util.AdminResponseCode;
import com.qf.util.AdminResponseUtil;
import com.qf.util.ResponseUtil;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * projectName:workspace_6
 * author:hyn
 * time:2021/11/25 22:23
 * description:后台修改密码
 */
@CrossOrigin("*")
@RequestMapping("/admin/profile")
@RestController
public class AdminProfileController {
    @Autowired
    private DtsAdminService adminService;
    @RequestMapping("password")
    public Object savePassword(@RequestBody Map<String,String> map){
        String oldPassword = map.get("oldPassword");
        String newPassword = map.get("newPassword");
        String newPassword2 = map.get("newPassword2");
        if(!newPassword.equalsIgnoreCase(newPassword2)){
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_OLDANDNEW_PASSWORD);
        }
        BCryptPasswordEncoder bpe = new BCryptPasswordEncoder();
        String newPwd = bpe.encode(newPassword);
//        String oldPwd = bpe.encode(oldPassword);
        Subject currentUser = SecurityUtils.getSubject();
        DtsAdmin admins = (DtsAdmin) currentUser.getPrincipal();
        String nowPwd = admins.getPassword();

        if(!bpe.matches(oldPassword, nowPwd)){
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_OLD_PASSWORD);
        }

        adminService.updatePassword(newPwd,admins.getId());
        admins.setPassword(newPwd);

//        currentUser.logout();
//        log.debug("退出");
//        log.debug("退出");


        return ResponseUtil.ok();
    }

}
